package com.yyfax.ph.personal.authority.bankcard.view.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.yyfax.common.CLog;
import com.yyfax.common.form.*;
import com.yyfax.common.tools.RobolectricUtils;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yyfax.infrastructure.statistics.StatService;
import com.yyfax.ph.R;
import com.yyfax.ph.StatIDSet;
import com.yyfax.ph.base.PermissionActivity;
import com.yyfax.ph.base.YJPH;
import com.yyfax.ph.base.dialog.DialogBase;
import com.yyfax.ph.common.scan.bankcard.activity.CardRecoActivity;
import com.yyfax.ph.common.scan.idcard.activity.ScanIdCardActivity;
import com.yyfax.ph.common.utils.preferenceutils.PreferenceConstants;
import com.yyfax.ph.home.recommendloan.RecommendLoanActivity;
import com.yyfax.ph.personal.authority.bankcard.BankCardEvent;
import com.yyfax.ph.personal.authority.bankcard.model.GetOwnedBankModel;
import com.yyfax.ph.personal.authority.bankcard.presenter.BindCardPresenter;
import com.yyfax.ph.personal.authority.bankcard.presenter.GetOwnedBankPresenter;
import com.yyfax.ph.web.WebActivity;
import exocr.exocrengine.DictManager;

import java.net.ConnectException;

/**
 * "实名认证"功能模块
 * Created by ZhangXian on 2017/11/02.<br>
 * Copyright 2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class BindCardActivity extends PermissionActivity implements
		BindCardPresenter.View, GetOwnedBankPresenter.View, FormScanView.onScanClickListener {
	public static final String TAG = "BindCardActivity";

	public static final String FROM_HOME_FRAGMENT = "from_home_fragment";//首页推荐进来的
	public static final String LAST_PAGE = "LAST_PAGE";//上一页来源
//	public static final String CREDIT_RECOMMEND = "credit_recommend";//上一页来源

	private String mLastPage; //进来之前的上一页：1.首页推荐, 2.其他...
	private boolean mValidateBankCard; //是否合法的银行卡
//	private boolean mcreditRecommend;

	private static final int LOADER_BIND_CARD_ID = 801;
	private static final int LOADER_BANKCARD_ID = 802;
	private static final int LOADER_OWNEDBANK_ID = 803;
	private DialogBase mDialog;

	private static final String BANK_CODE = "bank_code";
	private static final String PHONENUMBER = "phone_number";
	private static final String IDCARD = "id_card";
	private static final String BANK_NAME_K = "bank_name_k";
	private static final String BANK_CARD_NUMBER = "bank_card_numbe";
	private static final String USERNAME = "user_name";
	private static final String HAS_REAL_NAME = "has_real_name";
	@BindView(R.id.bind_tips_tv)
	TextView mBindTipsTv;
	/**
	 * 持卡人姓名
	 */
	private FormRow mNameFr;
	/**
	 * 身份证号码
	 */
	private FormRow mIdCardFr;
	/**
	 * 开户银行
	 */
	private FormRow mBankNameFr;
	/**
	 * 银行卡号
	 */
	private FormRow mBankCardFr;
	/**
	 * 手机号码
	 */
	private FormRow mPhoneFr;

	private String mBankCode;

	private String mUserName;
	private String mBankCardNumber;
	private String mIDCard;
	private String mBankName;
	private String mPhoneNumber;
	private boolean mHasRealName = false; // 是否已实名过
	private boolean mClickBindBtn;//是否点击"绑定"按钮
	private BindCardPresenter mBindCardPresenter;
	private GetOwnedBankPresenter mGetOwnedBankPresenter;
	private boolean mHasFocus;//银行卡输入框是否有焦点
	private int mPermissionRequestCodeCamera = DEFAULT_PERMISSION_REQUEST_CODE_CAMERA_EXTERNAL_STORAGE;

	public static void start(Activity aty, Intent intent) {
		aty.startActivity(intent);
	}

	public static void start(Activity aty) {
		Intent intent = new Intent(aty, BindCardActivity.class);
		aty.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getSupportLoaderManager().initLoader(LOADER_BIND_CARD_ID, null, this);
		getSupportLoaderManager().initLoader(LOADER_BANKCARD_ID, null, this);
		getSupportLoaderManager().initLoader(LOADER_OWNEDBANK_ID, null, this);
		ButterKnife.bind(this);

		if (savedInstanceState != null) {
			readBundle(savedInstanceState);
		} else {
			Intent intent = getIntent();
			mUserName = intent.getStringExtra(GetBindCardActivity.NAME);
			mIDCard = intent.getStringExtra(GetBindCardActivity.CARD_ID);
			mLastPage = intent.getStringExtra(LAST_PAGE);
//			mcreditRecommend = intent.getBooleanExtra(CREDIT_RECOMMEND, true);
			if (!TextUtils.isEmpty(mUserName) && !TextUtils.isEmpty(mIDCard)) {
				mHasRealName = true;
			} else {
				mHasRealName = false;
			}
		}
		initData();
	}

	private void initData() {
		if (!TextUtils.isEmpty(mPhoneNumber)) {
			mPhoneFr.setText(mPhoneNumber);
		}
		if (!TextUtils.isEmpty(mIDCard)) {
			mIdCardFr.setText(mIDCard);
		}
		if (!TextUtils.isEmpty(mBankName)) {
			mBankNameFr.setText(mBankName);
		}
		if (!TextUtils.isEmpty(mBankCardNumber)) {
			mBankCardFr.setText(mBankCardNumber);
		}
		if (!TextUtils.isEmpty(mUserName)) {    //名字
			mNameFr.setText(mUserName);
		}

		if (mHasRealName) {
			mBindTipsTv.setVisibility(View.VISIBLE);
			(mNameFr.getRightView()).setFocusable(false);        //持卡人和身份证设置不可编辑
			(mNameFr.getRightView()).setFocusableInTouchMode(false);
			((ClearEditText) mNameFr.getRightView()).setKeyListener(null);
			mNameFr.setmCanEdit(false);
			((FormScanView) mIdCardFr.getRightView()).mREditText.setFocusable(false);
			((FormScanView) mIdCardFr.getRightView()).mREditText.setFocusableInTouchMode(false);
			((FormScanView) mIdCardFr.getRightView()).mREditText.setKeyListener(null);
			mIdCardFr.setmCanEdit(false);
			((FormScanView) mIdCardFr.getRightView()).mIdCardIb.setImageDrawable(null);
			mIdCardFr.setBackgroundColor(getResources().getColor(R.color.color_ffffff));
//			((ClearEditText) mNameFr.getRightView()).setTextColor(getResources().getColor(R.color.color_cccccc));
//			((FormScanView) mIdCardFr.getRightView()).mREditText.setTextColor(getResources().getColor(R.color.color_cccccc));
		} else {
			mBindTipsTv.setVisibility(View.GONE);
		}
	}

	/**
	 * 回显数据
	 */
	private void readBundle(Bundle savedInstanceState) {
		mUserName = savedInstanceState.getString(USERNAME);        //名字
		mIDCard = savedInstanceState.getString(IDCARD);        //身份证号码
		mBankName = savedInstanceState.getString(BANK_NAME_K);    //开户银行
		mBankCardNumber = savedInstanceState.getString(BANK_CARD_NUMBER);    //银行卡号
		mPhoneNumber = savedInstanceState.getString(PHONENUMBER);    //手机号码
		mHasRealName = savedInstanceState.getBoolean(HAS_REAL_NAME);    //是否已实名
	}

	@Override
	public int getContentViewRes() {
		return R.layout.bind_card_activity_layout;
	}

	@Override
	protected void onStart() {
		super.onStart();
		if (!DictManager.getInstance().hasInit() && !RobolectricUtils.isARobolectricUnitTest()) {
			DictManager.getInstance().initDict(this, null);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		getSupportLoaderManager().destroyLoader(LOADER_BIND_CARD_ID);
		getSupportLoaderManager().destroyLoader(LOADER_BANKCARD_ID);
		getSupportLoaderManager().destroyLoader(LOADER_OWNEDBANK_ID);
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_BIND_CARD_ID:
				return new PresenterLoader<>(this, new BindCardPresenter.Generator());
			case LOADER_OWNEDBANK_ID:
				return new PresenterLoader<>(this, new GetOwnedBankPresenter.Generator());
		}
		return null;
	}

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_BIND_CARD_ID:
				mBindCardPresenter = (BindCardPresenter) data;
				mBindCardPresenter.attach(this);
				break;
			case LOADER_OWNEDBANK_ID:
				mGetOwnedBankPresenter = (GetOwnedBankPresenter) data;
				mGetOwnedBankPresenter.attach(this);
				break;
		}
	}

	@Override
	public void initContentView() {
		setBtnRightVisible(false);
		setTitleLeftVisible(false);
		setTitleVisible(true);
		setTitle(R.string.certification);

		mNameFr = (FormRow) findViewById(R.id.name_layout);
		mIdCardFr = (FormRow) findViewById(R.id.id_card_layout);
		((FormScanView) mIdCardFr.getRightView()).setOnScanClickListener(this);
		mBankNameFr = (FormRow) findViewById(R.id.bank_name_layout);
		mBankNameFr.setOnClickListener(this);
		mBankCardFr = (FormRow) findViewById(R.id.bank_card_layout);
		((FormScanView) mBankCardFr.getRightView()).setOnScanClickListener(this);
		mPhoneFr = (FormRow) findViewById(R.id.phone_layout);
		((FormScanView) mBankCardFr.getRightView()).setOnFocusChangeListener(new FormScanView.OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				mHasFocus = hasFocus;
				if (!hasFocus) {//失去焦点，检查银行卡合法性
					String bankCard = ((FormScanView) mBankCardFr.getRightView()).getFormText();
					if (!TextUtils.isEmpty(bankCard)) {
						mClickBindBtn = false;
						mGetOwnedBankPresenter.getOwnedBank(bankCard);
					}
				} else {
					mBankNameFr.setText("");
				}
			}
		});
		((FormScanView) mBankCardFr.getRightView()).mREditText.addTextChangedListener(new NumSpaceTextWatcher(((FormScanView) mBankCardFr.getRightView()).mREditText));
	}

	@Override
	public void onBackBtnPressed() {
		super.onBackBtnPressed();
		finish();
	}

	@Override
	public void onBackPressed() {
		super.onBackPressed();
		finish();
	}

	private boolean idOrBankFlag = false;

	private void goToScanIdCard() {
		if (hardwareSupportCheck()) {
			Intent intent = new Intent(this, ScanIdCardActivity.class);
			intent.putExtra(ScanIdCardActivity.BOTH_DIRECTION, false);
			ScanIdCardActivity.startForResult(this, intent, ScanIdCardActivity
					.MSG_GET_SCAN_ID_CARD);
		}
	}

	private void goToScanBankCard() {
		//检查权限
		if (hardwareSupportCheck()) {
			CardRecoActivity.start(this);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == CardRecoActivity.msg_scan_bank_card) {//扫描银行卡
			if (resultCode == Activity.RESULT_OK) {
				if (data.hasExtra(CardRecoActivity.bank_card_number_flag)) {
					String cardNum = data.getStringExtra(CardRecoActivity.bank_card_number_flag);
					mBankCardFr.setText(cardNum);
					mClickBindBtn = false;
					mGetOwnedBankPresenter.getOwnedBank(cardNum);
				}
			}
		} else if (requestCode == ScanIdCardActivity.MSG_GET_SCAN_ID_CARD) {//扫描身份证
			if (resultCode == Activity.RESULT_OK) {
				if (data.hasExtra(ScanIdCardActivity.SCAN_ID_RESULT)) {
					String idCardNum = data.getStringExtra(ScanIdCardActivity.SCAN_ID_RESULT);
					mIdCardFr.setText(idCardNum);
					mIdCardFr.validate();//扫描身份证后, 检查身份是否正确
				}
				if (data.hasExtra(ScanIdCardActivity.SCAN_ID_NAME_RESULT)) {
					String cardName = data.getStringExtra(ScanIdCardActivity.SCAN_ID_NAME_RESULT);
					mNameFr.setText(cardName);
				}
			}
		}
	}

	/**
	 * 点击绑定按钮
	 */
	public void bindCard() {
		if (!mNameFr.validate()) {
			return;
		}
		if (!mHasRealName) { //绑卡标志位为1时,点击确认按钮不校验身份证号码
			if (!mIdCardFr.validate()) {
				return;
			}
		}
		if (!mBankCardFr.validate()) {
			return;
		}
		if (!mValidateBankCard) {
			showToast(R.string.please_input_correct_bank_card);
			return;
		}

		if (!mPhoneFr.validate()) {
			return;
		}
		mClickBindBtn = true;
		mBindCardPresenter.bindCard(mNameFr.getText().toString(), mIdCardFr.getText().toString(),
				mPhoneFr.getText().toString(), mBankCode, mBankCardFr.getText().toString());
	}


	@Override
	public void bindCardFailure(String tips) {
		if (RobolectricUtils.isARobolectricUnitTest()) {
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage(tips);
			builder.setPositiveButton(getString(R.string.confirm),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialogInterface, int arg1) {
							dialogInterface.dismiss();
						}
					}
			);
			AlertDialog mAlertDialog = builder.create();
			mAlertDialog.setCanceledOnTouchOutside(false);
			mAlertDialog.setCancelable(false);
			mAlertDialog.show();
		} else {
			showTipsDialog(tips);
		}

	}

	@Override
	public void onFunctionalError(final Throwable e, boolean autoTips) {
		if (mClickBindBtn) {
			runOnUiThread(new Runnable() {
				@Override
				public void run() {
					CLog.d(TAG, "showErrorToast()");
					if (e instanceof ConnectException) {
						Toast.makeText(BindCardActivity.this, R.string.common_network_unavailable, Toast.LENGTH_SHORT).show();//如果是没开网络
						CLog.i(TAG, "onError(): ConnectException");
					} else {
						Toast.makeText(BindCardActivity.this, R.string.system_is_busy, Toast.LENGTH_SHORT).show();//如果是接口慢、异常、无返回等情况
						CLog.i(TAG, "onError(): SocketTimeoutException");
					}
				}
			});
			onFunctionalCompleted(autoTips);
		} else {
			super.onFunctionalError(e, autoTips);
		}
	}

	/**
	 * 绑卡成功,传递数据去下一个界面
	 */
	@Override
	public void bindCardSuccess(String tips, String name, String cardNumber, String bankName, String bankCode) {
		YJPH.getInstance().getPreferenceManager().savePreference(PreferenceConstants.SP_KEY_USER_NAME, name);
		EventAgent.postSticky(new BankCardEvent());
		if (FROM_HOME_FRAGMENT.equals(mLastPage)) {//如果是从首页进来的，绑卡成功跳到推荐贷款页
			if (RobolectricUtils.isARobolectricUnitTest()) {
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle(R.string.bind_bank_card_success_title);
				builder.setMessage(getString(R.string.bind_bank_card_success_content));
				builder.setPositiveButton(getString(R.string.confirm),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialogInterface, int arg1) {
								dialogInterface.dismiss();
								RecommendLoanActivity.start(BindCardActivity.this);
								finish();
							}
						}
				);
				AlertDialog mAlertDialog = builder.create();
				mAlertDialog.setCanceledOnTouchOutside(false);
				mAlertDialog.setCancelable(false);
				mAlertDialog.show();
			} else {
				if (mDialog != null && mDialog.isShowing()) {
					return;
				}
				mDialog = new DialogBase(this, getString(R.string.bind_bank_card_success_title), getString(R.string.bind_bank_card_success_content),
						getResources().getString(R.string.confirm),
						new DialogBase.BottomOneClickListener() {

							@Override
							public void bottomOneClick(DialogBase dialog) {
								dialog.dismiss();
//								if (mcreditRecommend) {
									RecommendLoanActivity.start(BindCardActivity.this);
//								} else {
//									NoCreditScanActivity.start(BindCardActivity.this);
//								}
								finish();
							}
						}, false);
				mDialog.show();
			}
		} else {
			showToast(tips);
			GetBindCardActivity.start(this, cardNumber, name, bankName, bankCode);
			finish();
		}
	}

	//扫描银行卡
	@Override
	public void onScanClick(View view) {
		switch (view.getId()) {
			case R.id.id_card_layout://点击扫描身份证图标
				idOrBankFlag = false;
				if (hasCameraPermission(mPermissionRequestCodeCamera)) {
					Intent intent = new Intent(this, ScanIdCardActivity.class);
					intent.putExtra(ScanIdCardActivity.BOTH_DIRECTION, false);
					ScanIdCardActivity.startForResult(this, intent, ScanIdCardActivity
							.MSG_GET_SCAN_ID_CARD);
				}
				break;
			case R.id.bank_card_layout://点击扫描银行卡图标
				idOrBankFlag = true;
				if (hasCameraPermission(mPermissionRequestCodeCamera)) {
					CardRecoActivity.start(this);
				}
				break;
		}
	}

	@Override
	protected void permissionsAllGrantedSuccess(int requestCode) {
		if (requestCode == mPermissionRequestCodeCamera){
			if (idOrBankFlag) {
				goToScanBankCard();
			} else {
				goToScanIdCard();
			}
		}
	}

	/**
	 * 保存数据
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putString(BANK_CODE, mBankCode);
		outState.putString(USERNAME, mNameFr.getText().toString());    //名字
		outState.putString(IDCARD, mIdCardFr.getText().toString());    //身份证
		outState.putString(BANK_NAME_K, mBankNameFr.getText().toString());    //开户银行
		outState.putString(BANK_CARD_NUMBER, mBankCardFr.getText().toString());    //银行卡号
		outState.putString(PHONENUMBER, mPhoneFr.getText().toString());    //手机号码
		outState.putBoolean(HAS_REAL_NAME, mHasRealName);    //是否已实名
	}


	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (savedInstanceState != null) {
			mBankCode = savedInstanceState.getString(BANK_CODE);
		}
	}


	@OnClick({R.id.name_layout, R.id.id_card_layout, R.id.bank_name_layout, R.id.bind_card_bottom_layout, R.id
			.bind_card_confirm_btn, R.id.browse_support_banks_tv})
	public void onViewClick(View view) {
		super.onClick(view);
		switch (view.getId()) {
			case R.id.name_layout://在第二次绑定的时候，持卡人和身份证都不能修改，点击这里让银行卡输入框失去焦点
				mBankCardFr.clearFocus();
				mBankNameFr.setFocusableInTouchMode(true);
				mBankNameFr.requestFocus();
				break;
			case R.id.id_card_layout://在第二次绑定的时候，持卡人和身份证都不能修改，点击这里让银行卡输入框失去焦点
				mBankCardFr.clearFocus();
				mBankNameFr.setFocusableInTouchMode(true);
				mBankNameFr.requestFocus();
				break;
			case R.id.bank_name_layout://开户银行
				mBankCardFr.clearFocus();
				mBankNameFr.setFocusableInTouchMode(true);
				mBankNameFr.requestFocus();
				break;
			case R.id.bind_card_bottom_layout://下边布局,用于隐藏键盘
				YJPH.hideInputWindow(this);
				break;
			case R.id.browse_support_banks_tv://查看支持银行卡列表
				StatService.onEvent(YJPH.getInstance(), StatIDSet.EVENT_ID_E029);
				WebActivity.start(this, getString(R.string.view_banks), WebActivity.TYPE_BANK_LIST);
				break;
			case R.id.bind_card_confirm_btn://确认按钮
				mBankCardFr.clearFocus();
				mBankNameFr.setFocusableInTouchMode(true);
				mBankNameFr.requestFocus();
				bindCard();
				break;
		}
	}

	/**
	 * 根据输入银行卡号，选择开户银行
	 *
	 * @param bank
	 */
	@Override
	public void getOwnedBankSuccess(GetOwnedBankModel.OwnedBank bank) {
		if (!mHasFocus) {
			mValidateBankCard = true;
			((FormSelectView) mBankNameFr.getRightView()).mRTextView.setTextColor(YJPH.getInstance().color(R.color.color_000000));
			mBankNameFr.setText(bank.bankDescription);
			mBankCode = bank.bankCode;
		}
	}

	/**
	 * 不支持银行
	 */
	@Override
	public void notSupportBank() {
		if (!mHasFocus) {
			mValidateBankCard = false;
			((FormSelectView) mBankNameFr.getRightView()).mRTextView.setTextColor(YJPH.getInstance().color(R.color.color_f05b47));
			mBankNameFr.setText(getString(R.string.not_support_bank_tips));
		}
	}

	/**
	 * 输入卡号是信用卡
	 */
	@Override
	public void isCreditCard() {
		if (!mHasFocus) {
			mValidateBankCard = false;
			((FormSelectView) mBankNameFr.getRightView()).mRTextView.setTextColor(YJPH.getInstance().color(R.color.color_f05b47));
			mBankNameFr.setText(getString(R.string.not_support_credit_card_tips));
		}
	}

	/**
	 * 获取失败，银行卡号错误
	 *
	 * @param tips
	 */
	@Override
	public void getOwnedBankFailure(String tips) {
		if (!mHasFocus) {
			mValidateBankCard = false;
			((FormSelectView) mBankNameFr.getRightView()).mRTextView.setTextColor(YJPH.getInstance().color(R.color.color_fe6753));
			mBankNameFr.setText(getString(R.string.error_bank_card_info_tips));
		}
	}

	public void setLastPage(String lastPage) {
		mLastPage = lastPage;
	}

	public String getLastPage() {
		return mLastPage;
	}
}
